using AutoMapper;
using MediatR;
using ThreeTeams.Domain.ThreeTeams.Domain.Entities;
using WMS.Api.Application.Commands;
using WMS.Common;
using WMS.Infrastructure;

namespace WMS.Api.Application.CommandHandlers
{
    /// <summary>
    /// 创建产品命令处理程序
    /// </summary>
    public class CreateProductCommandHandler : IRequestHandler<CreateProductCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Product> _productRepository;
        private readonly IMapper _mapper;

        public CreateProductCommandHandler(IBaseRepository<Product> productRepository, IMapper mapper)
        {
            _productRepository = productRepository;
            _mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(CreateProductCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>("创建产品");

            try
            {
                // 检查SKU是否已存在
                var existingProduct = await _productRepository.GetNewValueAsync(p => p.SKU == request.Product.SKU);
                if (existingProduct != null)
                {
                    result.code = StatusCodeEnum.DataExist;
                    result.msg = $"SKU '{request.Product.SKU}' 已存在";
                    return result;
                }

                var product = _mapper.Map<Product>(request.Product);
                var affectedRows = await _productRepository.AddNewAsync(product);

                result.Success(affectedRows);
            }
            catch (Exception ex)
            {
                result.code = StatusCodeEnum.Fail;
                result.msg = $"创建产品失败：{ex.Message}";
            }

            return result;
        }
    }
} 